package com.flykoc.lightinggem.listener;

import com.flykoc.lightinggem.api.GemAPI;
import com.flykoc.lightinggem.dao.GemDao;
import com.flykoc.lightinggem.dto.LightingGem;
import com.google.common.collect.Lists;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.FurnaceSmeltEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.List;

/**
 * 熔炼完毕监听
 *
 * @author Zoyn
 * @since 2017-10-21
 */
public class FurnaceSmeltListener implements Listener {

    @EventHandler
    public void onSmelt(FurnaceSmeltEvent e) {
        ItemStack source = e.getSource();
        ItemStack fuel = FurnaceBurnListener.fuelItem.get(e.getBlock().hashCode());
        // 该变量是原剑的克隆,用于设置煅烧后的物品
        ItemStack smeltedItemStack = source.clone();

        // 宝石与武器检查
        if (GemAPI.isGem(fuel)) {
            if (GemAPI.isWeapon(source)) {
                LightingGem gem = GemDao.getGem(fuel);
                if (gem == null) {
                    return;
                }
                ItemMeta itemMeta = smeltedItemStack.getItemMeta();
                if (itemMeta == null) {
                    return;
                }

                if (source.getItemMeta().hasLore()) {
                    List<String> lore = itemMeta.getLore();
                    // 判断是否存在 闪电附加 字样
                    if (lore.stream().anyMatch(s -> s.contains("闪电附加"))) {
                        for (int i = 0; i < lore.size(); i++) {
                            if (lore.get(i).contains("闪电附加")) {
                                lore.set(i, "§e闪电附加+" + gem.getOdds() + "%");
                            }
                        }
                    } else {
                        lore.add("§e闪电附加+" + gem.getOdds() + "%");
                    }

                    itemMeta.setLore(lore);
                    smeltedItemStack.setItemMeta(itemMeta);
                } else { // 无Lore的时候
                    List<String> lore = Lists.newArrayList();
                    lore.add("§e闪电附加+" + gem.getOdds() + "%");
                    itemMeta.setLore(lore);
                    smeltedItemStack.setItemMeta(itemMeta);
                }
            }
        }
        e.setResult(smeltedItemStack);
    }
}
